#include "paihang.h"
#include "ui_paihang.h"
#include <QDebug>

PaiHang::PaiHang(QList<User *> users, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::PaiHang)
{
    ui->setupUi(this);

    this->temp = users;

    this->userNum = users.size(); //玩家人数初始化

    this->initScene(); //初始化窗口
}

PaiHang::~PaiHang()
{
    delete ui;
}

void PaiHang::on_back_clicked()
{
    this->clearIt(); //清空排行榜
    emit showMe(); //发送显示我界面
    this->hide(); //隐藏当前窗口
}

//初始化窗口
void PaiHang::initScene(){
    setWindowTitle(GAME_NAME); //设置窗口标题
//    setWindowIcon(QIcon(GAME_ICON_)); //设置窗口图标
    //this->initQLabel(); //初始化标签
}

//制作排行榜
void PaiHang::zhiZuo(){
    //this->clearIt();
    this->sortPaiHang(); //排序排行榜
    for(int i = 0; i < this->userNum; i++){
        lb[i * 3 + 0] = new QLabel(this);
        lb[i * 3 + 0]->setText(QString::number(i + 1));
        lb[i * 3 + 0]->setGeometry(10, 60 + 20 * i, 72, 15);
        lb[i * 3 + 1] = new QLabel(this);
        lb[i * 3 + 1]->setText(this->tempShuZu[i]->userName);
        lb[i * 3 + 1]->setGeometry(120, 60 + 20 * i, 72, 15);
        lb[i * 3 + 2] = new QLabel(this);
        lb[i * 3 + 2]->setText(this->tempShuZu[i]->score);
        lb[i * 3 + 2]->setGeometry(240, 60 + 20 * i, 72, 15);
    }
}

//清空排行榜
void PaiHang::clearIt(){
    this->userNum = this->temp.size();
    for(int i = 0; i < this->userNum; i++){
        lb[i * 3 + 0]->clear();
        lb[i * 3 + 1]->clear();
        lb[i * 3 + 2]->clear();
    }
}

//接收信号制作排行榜
void PaiHang::recZhiZuoPaiHang(){
    this->zhiZuo(); //制作排行榜
}

//排序排行榜
void PaiHang::sortPaiHang(){

    for(int i = 0; i < this->userNum; i++){
        this->tempShuZu[i] = new User(temp.at(i)->userName, temp.at(i)->passWord, temp.at(i)->score, temp.at(i)->post, temp.at(i)->nickName);
         //qDebug() << this->tempShuZu[i]->score;
    }

    int k = 0;
    for(int i = 0; i < this->userNum - 1; i++){
        k = i;
        for(int j = i + 1; j < this->userNum; j++){
            if(tempShuZu[k]->score.compare(tempShuZu[j]->score) < 0){
                k = j; //记录最大数的下标
            }
        }

        if(k != i){
            User* t;
            t = new User(tempShuZu[i]->userName, tempShuZu[i]->passWord, tempShuZu[i]->score, tempShuZu[i]->post, tempShuZu[i]->nickName);
            tempShuZu[i] = new User(tempShuZu[k]->userName, tempShuZu[k]->passWord, tempShuZu[k]->score, tempShuZu[k]->post, tempShuZu[k]->nickName);
            tempShuZu[k] = new User(t->userName, t->passWord, t->score, t->post, t->nickName);
        }
    }

}
